package com.chenqi.interceptor;

import com.chenqi.utils.JsonData;
import com.chenqi.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @description: 登陆拦截器
 * @program: ardaicommunity
 * @author: ChenQi
 * @create: 2021-03-2021/3/9-15-26
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 发送请求时，拦截请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //token一般放在请求里面
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }
        //如果token不为空
        if (StringUtils.isNotBlank(accessToken)){
            Claims claims = JwtUtils.checkJWT(accessToken);
            //token过期了
            if (claims == null) {
                sendMessage(response, JsonData.BuildError("登陆过期"));
                return false;
            }
            int id = (int) claims.get("id");
            String username = (String) claims.get("username");
            String avatar = (String) claims.get("avatar");
            request.setAttribute("user_id", id);
            request.setAttribute("user_username", username);
            request.setAttribute("user_avatar", avatar);
            return true;
        }
        sendMessage(response, JsonData.BuildError("请先登陆"));
        return false;
    }

    public static void sendMessage(HttpServletResponse response, Object obj) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        String content = objectMapper.writeValueAsString(obj);
        writer.print(content);
        writer.close();
        response.flushBuffer();
    }
}
